﻿using System;
using System.Windows.Controls;
using System.Collections.ObjectModel;
using System.ServiceModel;
//using System.Windows.Browser;
using Microsoft.Maps.MapControl;
using System.Windows.Browser;
using MyFloridaHouse.ServiceConn.BingGeocodeService;


namespace MyFloridaHouse.SilverlightOpenDistricts
{
    public partial class MainPage : UserControl
    {
        public const double GEOCODE_ZOOM_LEVEL = 17;

        private int geocodesInProgress;


        private MapGeocodeLayer geocodeLayer;
        private MapGeocodeLayer GeocodeLayer
        {
            get
            {
                if (null == geocodeLayer)
                {
                    geocodeLayer = new MapGeocodeLayer(MyXamlMainMap);
                }
                return geocodeLayer;
            }
        }

        private GeocodeServiceClient geocodeClient;
        private GeocodeServiceClient GeocodeClient
        {
            get
            {
                if (null == geocodeClient)
                {
                    //Handle http/https
                    bool httpsUriScheme = HtmlPage.Document.DocumentUri.Scheme.Equals(Uri.UriSchemeHttps);
                    BasicHttpBinding binding = httpsUriScheme ? new BasicHttpBinding(BasicHttpSecurityMode.Transport) : new BasicHttpBinding(BasicHttpSecurityMode.None);
                    UriBuilder serviceUri = new UriBuilder("http://dev.virtualearth.net/webservices/v1/GeocodeService/GeocodeService.svc");
                    if (httpsUriScheme)
                    {
                        //For https, change the UriSceheme to https and change it to use the default https port.
                        serviceUri.Scheme = Uri.UriSchemeHttps;
                        serviceUri.Port = -1; 
                    }

                    //Create the Service Client
                    geocodeClient = new GeocodeServiceClient(binding, new EndpointAddress(serviceUri.Uri));
					geocodeClient.GeocodeCompleted += new EventHandler<GeocodeCompletedEventArgs>(client_GeocodeCompleted);
                }
                return geocodeClient;
            }
        }


        public void GeocodeAddress(string address)
        {
            if (address.Length > 0)
            {
                GeocodeRequest request = new GeocodeRequest();
                request.Culture = MyXamlMainMap.Culture;
                request.Query = address;
                // Don't raise exceptions.
                request.ExecutionOptions = new ExecutionOptions();
                request.ExecutionOptions.SuppressFaults = true;

                // Only accept results with high confidence.
                request.Options = new GeocodeOptions();
                // Using ObservableCollection since this is the default for Silverlight proxy generation.
                request.Options.Filters = new ObservableCollection<FilterBase>();
                ConfidenceFilter filter = new ConfidenceFilter();
                filter.MinimumConfidence = Confidence.Medium;
                request.Options.Filters.Add(filter);

                //Output.Text = "< geocoding " + address + " >";
                geocodesInProgress++;

                // use the Bing map to get the credentials that were used to create it
                MyXamlMainMap.CredentialsProvider.GetCredentials(
                    ( credentials) =>
                    {
                        //Pass in credentials for web services call.
                        //Replace with your own Credentials.
						request.Credentials.ApplicationId = credentials.ApplicationId;
                        request.Credentials.Token = credentials.Token;


                        // Make asynchronous call to fetch the data ... pass state object.
                        GeocodeClient.GeocodeAsync(request, address);
                    });
            }

        }

        private void client_GeocodeCompleted(object sender, GeocodeCompletedEventArgs e)
        {
        //    // Callback when the geocode is finished.
        //    // todo: move all references to geocodeResultWindow items to viewModel
        //    string outString = "";
        //    geocodesInProgress--;
        //    geocodeResultWindow.lbl_Status.Content = "Found " + e.Result.Results.Count.ToString() + " locations" ;
        //    try
        //    {
        //        if (e.Result.ResponseSummary.StatusCode != BingGeocodeService.ResponseStatusCode.Success)
        //        {
        //            geocodeResultWindow.Visibility = Visibility.Visible;
        //            geocodeResultWindow.lbl_Status.Content = "error geocoding ... status <" + e.Result.ResponseSummary.StatusCode.ToString() + ">";
        //        }
        //        else if (0 == e.Result.Results.Count)
        //        {
        //            geocodeResultWindow.Visibility = Visibility.Visible;
        //        }
        //        else if (1 == e.Result.Results.Count)
        //        {
        //            onGeocodeSelected(this, new GeocodeSelectedEventArgs(e.Result.Results[0]));
                     
        //        }
        //        else
        //        {
        //            // todo: move this operation to viewModel
        //            geocodeResultWindow.Visibility = Visibility.Visible;
        //            geocodeResultWindow.geocodeResultList.ItemsSource = e.Result.Results;
        //        }
        //    }
        //    catch
        //    {
        //        outString = "Unable to map that address, sorry";
        //    }
        //    if (outString.Length > 0)
        //        MessageBox.Show(outString);
        }


    }
}
